package com.taptech.doufu.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.UIUtil;

public class BrowseSimpleActivity extends Activity {

    static WebView webView;
    TextView title;
    private String url = "";
    private String mTitle;

    private final int CLOSE_WEBVIEW = 6;
    // ui控件
    View progressBar;

    private int screenWidth = 1000;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_browse);
        webView = (WebView) findViewById(R.id.activity_answer_start_wb);
        title = (TextView) findViewById(R.id.activity_answer_start_title);
        url = getIntent().getStringExtra(Constant.URL);
        url = Constant.changeUrlHost(url);
        screenWidth = ScreenUtil2.getScreenWidthPixel(this);

        mTitle = getIntent().getStringExtra(Constant.TITLE);
        title.setText(mTitle);

        webView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");
        webView.addJavascriptInterface(new JavascriptInterface(this), "native");
        progressBar = findViewById(R.id.webview_progress_bar);


        WebSettings webSettings = webView.getSettings();
        webSettings.setBuiltInZoomControls(true);   // 设置支持缩放
        webSettings.setJavaScriptEnabled(true);     //支持js
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);

        webSettings.setAppCacheMaxSize(1024 * 1024 * 8); // 在API18后，将自动控制
        webSettings.setAllowFileAccess(true);       // 设置允许访问文件数据
        webSettings.setAppCacheEnabled(true);       //APP内存使能
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);


        webView.setWebChromeClient(new MyWebChromeClient(){

        });

        // “我来制作”上次图片的冲突
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                progressBar.setVisibility(View.GONE);

            }

            @Override
            public void onReceivedSslError(WebView view,SslErrorHandler handler, SslError error) {
                handler.cancel();
            }
        });
        webView.loadUrl(url);

    }


    private class MyWebChromeClient extends WebChromeClient {


        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            displayWebViewProgressBar(newProgress);
        }
    }


    /**
     * 展示进度条进度
     *
     * @param rate
     */
    private void displayWebViewProgressBar(int rate) {
        if (!progressBar.isShown() && rate > 0 && rate < 100) {
            progressBar.setVisibility(View.VISIBLE);
        }
        int progressWidth = (int) (rate / 100.0 * screenWidth);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) progressBar.getLayoutParams();
        layoutParams.width = progressWidth;
        progressBar.setLayoutParams(layoutParams);

    }


    @Override
    protected void onRestart() {
        super.onRestart();
        webView.loadUrl("javascript:onRestart()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        webView.loadUrl("javascript:onStop()");
    }



    public void backOnclick(View view) {
        finish();
    }

    // js通信接口
    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }



        @android.webkit.JavascriptInterface
        public void closeWebview() {
            mHandler.sendEmptyMessage(CLOSE_WEBVIEW);
        }



        @android.webkit.JavascriptInterface
        public void toast(String content) {
            UIUtil.toastMessage(BrowseSimpleActivity.this, content);
        }


    }




    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CLOSE_WEBVIEW:
                    backOnclick(null);
                    break;
                default:
                    break;
            }

        }

        ;
    };

    public void shareOnlick(View view) {

    }





    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        mHandler.sendEmptyMessage(CLOSE_WEBVIEW);
        super.onDestroy();

    }

    public static void startActivity(Context context,String url) {
        Intent intent = new Intent();
        intent.setClass(context, BrowseSimpleActivity.class);
        intent.putExtra(Constant.URL, url);
        context.startActivity(intent);
    }
}
